#!/usr/local/bin/python
# coding=utf-8
"""
图片压缩工具
"""
import os
import sys
import shutil
import log
import json
import xml.dom.minidom
from xml.dom.minidom import parse

from PIL import Image, ImageDraw

COMPRESS_QUALITY_JPG = 50
COMPRESS_QUALITY_PNG = 9
SCALE_RATE = 1.0

def get_newname_extend(filepath, postfix):
    fileWholeName = filepath.split('/')[-1]
    fileInfo = os.path.splitext(fileWholeName)
    return fileInfo[0] + postfix + '.png'


def compress_img(imagepath):
    img = Image.open(imagepath)
    w, h = img.size
    print('Original image size: %sx%s' % (w, h))
    img.thumbnail((int(w * 0.66), int(h * 0.66)))
    saveName = get_newname_extend(imagepath, '@2x')
    # 取得上层目录
    savedir = os.path.dirname(imagepath)
    savepath = os.path.join(savedir, saveName)
    img.save(savepath, 'png')
    os.rename(imagepath.split('/')[-1], get_newname_extend(imagepath, '@3x'))

def cut_image(src, target, cf):
    log.info( src+ target+ json.dumps(cf))
    # print 'cut_image -> ', target
    im = Image.open(src)
    cropedIm = im.crop((cf["x"], cf["y"], cf["x"] + cf["width"], cf["y"] + cf["height"]))
    # cropedIm.save(target,  quality=COMPRESS_QUALITY_JPG)
    cropedIm.save(target, compress_level=COMPRESS_QUALITY_PNG) #默认是6 9实际上也压缩不了多少



def parse_xml(dir_path):
    filelist = os.listdir(dir_path)
    for filename in filelist:
        fileInfo = os.path.splitext(filename)
        if fileInfo[1] == '.xml':
            log.info(filename)
            DOMTree = xml.dom.minidom.parse(dir_path + os.sep +filename)
            collection = DOMTree.documentElement
            src_file = ""
            if collection.hasAttribute("imagePath"):
                log.info( "Cut File Name : %s" % collection.getAttribute("imagePath"))
                src_file = dir_path + os.sep + collection.getAttribute("imagePath")
                new_dir = os.path.abspath('.') + os.sep + dir_path + os.sep + fileInfo[0]
                if os.path.exists(new_dir):
                    shutil.rmtree(new_dir)
                os.mkdir(new_dir)
            sub_images = collection.getElementsByTagName("SubTexture")
            for img in sub_images:
                #print "name: %s,x:%s,y=%s,w=%s,h=%s" % (img.getAttribute("name"), img.getAttribute("x"), img.getAttribute("y"), img.getAttribute("width"), img.getAttribute("height"))
                # list1 = ["name", "x", "y", "width", "height"]
                # list2 = [img.getAttribute("name"), img.getAttribute("x"), img.getAttribute("y"), img.getAttribute("width"), img.getAttribute("height")]
                obj = {
                    "name":img.getAttribute("name"),"x":int(img.getAttribute("x")),"y":int(img.getAttribute("y")),
                    "width":int(img.getAttribute("width")),"height":int(img.getAttribute("height"))
                }
                cut_image(src_file, dir_path + os.sep + fileInfo[0] + os.sep + img.getAttribute("name") + ".png", obj)


def parseXmls():
    filepath = raw_input('请输入要处理的文件夹名(相对路径)：\n')
    parse_xml(filepath)


#等比例压缩图片 只支持jpg     png参数需要变为compress_level(0-9)
def resizeImg(**args):
    args_key = {'ori_img':'','dst_img':'','dst_w':'','dst_h':'','save_q':75}
    arg = {}
    for key in args_key:
        if key in args:
            arg[key] = args[key]
        
    im = Image.open(arg['ori_img'])
    ori_w,ori_h = im.size
    widthRatio = heightRatio = None
    ratio = 1
    if (ori_w and ori_w > arg['dst_w']) or (ori_h and ori_h > arg['dst_h']):
        if arg['dst_w'] and ori_w > arg['dst_w']:
            widthRatio = float(arg['dst_w']) / ori_w #正确获取小数的方式
        if arg['dst_h'] and ori_h > arg['dst_h']:
            heightRatio = float(arg['dst_h']) / ori_h

        if widthRatio and heightRatio:
            if widthRatio < heightRatio:
                ratio = widthRatio
            else:
                ratio = heightRatio

        if widthRatio and not heightRatio:
            ratio = widthRatio
        if heightRatio and not widthRatio:
            ratio = heightRatio
            
        newWidth = int(ori_w * ratio)
        newHeight = int(ori_h * ratio)
    else:
        newWidth = ori_w
        newHeight = ori_h
        
    im.resize((newWidth,newHeight),Image.ANTIALIAS).save(arg['dst_img'],quality=arg['save_q'])

    '''
    image.ANTIALIAS还有如下值：
    NEAREST: use nearest neighbour
    BILINEAR: linear interpolation in a 2x2 environment
    BICUBIC:cubic spline interpolation in a 4x4 environment
    ANTIALIAS:best down-sizing filter
    '''

# 测试jpg完美支持，png电脑死活不压缩 
# resizeImg(ori_img='./release/backgrounds_2x/test.png',dst_img='./test.png',dst_w=569,dst_h=385,save_q=75)

